package com.sign.common.exception;


import com.alibaba.fastjson.JSONObject;
import com.ly.common.result.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

/**
 * Created by liyu on 2020/10/21.
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public void handleMethodArgumentNotValidException(MethodArgumentNotValidException e , HttpServletResponse response) throws IOException {
        String errorMsg = e.getBindingResult().getAllErrors()
                .stream()
                .map(objectError -> ((FieldError)objectError).getField() + ((FieldError)objectError).getDefaultMessage())
                .collect(Collectors.joining(","));
        JsonResult jsonResult = null;
        jsonResult = JsonResult.error(errorMsg);
        respWrite(response,jsonResult);
    }

    @ExceptionHandler(value = {ServiceException.class})
    public void serviceExceptionHandle(HttpServletRequest request , HttpServletResponse response , ServiceException e) throws IOException {
        JsonResult jsonResult = null;
        jsonResult = JsonResult.error(e.getMessage());
        StackTraceElement[] stackTraceElements= e.getStackTrace();
        String stackTrackMsg = null;
        if(stackTraceElements!= null && stackTraceElements.length>0){
            stackTrackMsg =stackTraceElements[0].toString();
        }
        respWrite(response,jsonResult);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public JsonResult validatedBindException(BindException e)
    {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return JsonResult.error(message);
    }

    @ExceptionHandler(value = {Exception.class})
    public void ExceptionHandle(HttpServletRequest request , HttpServletResponse response , Exception e) throws IOException {
        JsonResult jsonResult = null;
        jsonResult = JsonResult.error("服务器繁忙");
        respWrite(response,jsonResult);
    }

    private void respWrite(HttpServletResponse response,JsonResult jsonResult) throws IOException {
        String text =  JSONObject.toJSONString(jsonResult);
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(text);
        response.getWriter().flush();
        response.getWriter().close();
    }
}
